<template>
  <DialogBox :title="'编辑智能体'" v-model="dialogVisible" width="600" :before-clone="closeConfirm">
    <el-form
      ref="applicationFormRef"
      :model="applicationForm"
      :rules="rules"
      label-position="top"
      require-asterisk-position="right"
      @submit.prevent
    >
      <el-form-item label="智能体头像" prop="imgUrl" class="acatar_box">
        <span class="avatar_text">仅支持.png .jpg 格式，文件大小100KB以内</span>
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          v-model="applicationForm.imgUrl"
          action="/dada/base/anyone/file/upload"
          :headers="getHeaders()"
          :data="{
            bizType: 'AIAPPLICATION_AVATAR'
          }"
          :on-success="handleSuccess"
          :before-upload="handleBeforeAvatarUpload"
        >
          <div class="avatar-uploader-content">
            <div v-if="applicationForm.imgUrl" class="avatar-uploader-content-right">
              <img :src="applicationForm.imgUrl" class="avatar" />
              <div class="avatar-move">
                <svg-icon
                  icon-class="chakan"
                  style="margin-right: 10px"
                  @click.stop="handlePictureCardPreview(applicationForm.imgUrl)"
                />
                <svg-icon icon-class="shangchuan" />
              </div>
            </div>
            <div v-else class="avatar-uploader-content-right avatar-uploader-content-def">
              <div class="avatar-uploader-content-def-img">
                <img src="@/assets/agent/chat/upload-img.svg" alt="" />
                上传
              </div>
            </div>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="智能体名称" prop="name">
        <el-input
          v-model="applicationForm.name"
          maxlength="30"
          placeholder="请输入智能体名称"
          show-word-limit
          :disabled="applicationForm.type === 'WORK_FLOW'"
          @blur="applicationForm.name = applicationForm.name?.trim()"
        />
      </el-form-item>
      <el-form-item label="智能体描述" v-if="applicationForm.type !== 'WORK_FLOW'">
        <el-input
          v-model="applicationForm.applicationDesc"
          type="textarea"
          placeholder="请输入智能体描述"
          :rows="3"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="应用类型">
        <el-radio-group v-model="applicationForm.type" class="card__radio">
          <el-row :gutter="16">
            <el-col :span="12" v-if="applicationForm.type === 'SIMPLE'">
              <el-card shadow="never" class="active">
                <el-row justify="space-between" :gutter="10" style="height: 40px">
                  <el-col :span="22">
                    <div style="font-size: 14px">简单配置</div>
                    <el-text type="info" class="ellipsis" style="max-width: 210px">
                      适合新手创建小助手
                    </el-text>
                  </el-col>
                  <el-col :span="2">
                    <el-radio value="SIMPLE" size="large" />
                  </el-col>
                </el-row>
              </el-card>
            </el-col>
            <el-col :span="12" v-else>
              <el-card shadow="never" class="active">
                <el-row justify="space-between" :gutter="10" style="height: 40px">
                  <el-col :span="22">
                    <div style="font-size: 14px">高级编排</div>
                    <el-text type="info" class="ellipsis" style="max-width: 210px">
                      适合高级用户自定义小助手的工作流`
                    </el-text>
                  </el-col>
                  <el-col :span="2">
                    <el-radio value="WORK_FLOW" size="large" />
                  </el-col>
                </el-row>
              </el-card>
            </el-col>
          </el-row>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="请选择可见类型" prop="authState">
        <el-radio-group v-model="applicationForm.authState">
          <el-radio :value="item.value" :key="item.value" size="large" v-for="item in authOptions">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
        <div v-if="applicationForm.authState === 1" class="personnel-list" @click="openSelectDep">
          <div class="personnel-list-content ellipsis">
            <span v-for="item in applicationForm.employeeIdList" :key="item.id"
              >{{ item.name }},</span
            >
          </div>
          <div class="personnel-list-right">
            <span class="personnel-list-right-num">已选{{ applicationForm.employeeIdList?.length }}人</span>
            <img src="@/assets/agent/chat/kejian.svg" alt="">
          </div>
        </div>
      </el-form-item>
      <!-- 所属分类 -->
      <el-form-item label="所属分类" prop="classification">
        <el-select v-model="applicationForm.classification" placeholder="请选择所属分类">
          <el-option
            v-for="item in perTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer res_el-dialog__footer">
        <el-button @click.prevent="closeConfirm" :loading="loading"> 取消 </el-button>
        <el-button type="primary" @click="submitHandle(applicationFormRef)" :loading="loading">
          保存
        </el-button>
      </span>
    </template>
    <SelectDepartmentPersonnel ref="SelectDepartmentPersonnelRef" @submit="personHandle" />
    <!-- 预览弹框-->
    <el-dialog
      v-model="PreviewDialogVisible"
      append-to-body="true"
      width="600px"
      style="text-align: center"
      draggable="true"
    >
      <img w-full :src="PreviewdialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </DialogBox>
</template>
<script setup lang="ts">
import { cloneDeep, isEqual, isFunction } from 'lodash'
import { ref, watch, reactive } from 'vue'
import type { ApplicationFormType } from '@/api/type/application'
import type { FormInstance, FormRules } from 'element-plus'
import { MsgSuccess, MsgError, MsgConfirm } from '@/utils/message'
import useStore from '@/stores'
import { t } from '@/locales'
import SelectDepartmentPersonnel from '@/views/application/component/SelectDepartmentPersonnel.vue'
import { getHeaders } from '@/request/http'
import { authOptions } from '@/enums/application'
import type { UploadProps } from 'element-plus'
import { updateAiApplication, getDetails, check1 } from '@/servers/ai/api/zhinengti'
const { agent } = useStore()
const emit = defineEmits(['refresh'])
const perTypeList: any = ref([])
const SelectDepartmentPersonnelRef = ref()
// 图片预览
const PreviewdialogImageUrl = ref('')
const PreviewDialogVisible = ref(false)
const applicationFormRef = ref()
const loading = ref(false)
const dialogVisible = ref<boolean>(false)
const applicationForm = ref<ApplicationFormType | any>({
  id: '',
  maxId: '',
  name: '', // 	智能体名称
  applicationDesc: '', // 智能体描述
  imgUrl: '', // 图片地址
  classification: '', // 分类
  type: '', // 智能体类型
  authState: 0, // 授权状态
  employeeIdList: [] // 自定义可见范围选中的人
})
const oldRow: any = ref({})

/** 智能体名称校验 */
const validateNameDuplicate = async (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('智能体名称不能为空'));
    return;
  }

  if(oldRow.value.name === value) {
    return callback();
  }

  try {
    const res = await check1({ name: value });
    if (res.data.data) {
      callback();
    } else {
      callback(new Error('智能体名称重复，请重新输入'));
    }
  } catch (error) {
    callback(new Error('智能体名称重复，请重新输入'));
  }
};

const validateNameEmpty = (rule: any, value: string, callback: any) => {
  if (!value || value.trim() === '') {
    callback(new Error('智能体名称不能为空'));
  } else if (value.trim().length > 30) {
    callback(new Error('智能体名称长度不能大于30个字符'));
  }  else {
    callback();
  }
};

const validateNameSpecialChars = (rule: any, value: string, callback: any) => {
  const specialChars = /[*?"<>]/;
  if (specialChars.test(value)) {
    callback(new Error('智能体名不能包含特殊符号：*？"<>'));
  } else {
    callback();
  }
};

const rules = reactive<FormRules<ApplicationFormType>>({
  name: [
    { required: true, validator: validateNameEmpty, trigger: 'blur' },
    { validator: validateNameSpecialChars, trigger: 'blur' },
    { validator: validateNameDuplicate, trigger: 'blur' },
  ],
  desc: [
    {
      max: 100,
      message: '智能体描述长度不能大于100个字符',
      trigger: 'change'
    }
  ],
  model_id: [
    {
      required: false,
      message: t('views.application.applicationForm.form.aiModel.placeholder'),
      trigger: 'change'
    }
  ],
  categorize: [
    {
      required: true,
      message: '请选择分类',
      trigger: 'change'
    }
  ],
  dept: [
    {
      required: true,
      message: '请选择部门',
      trigger: 'change'
    }
  ]
})

watch(dialogVisible, (bool) => {
  if (!bool) {
    applicationForm.value = {
      id: '',
      maxId: '',
      name: '', // 	智能体名称
      applicationDesc: '', // 智能体描述
      imgUrl: '', // 图片地址
      classification: '', // 分类
      type: '', // 智能体类型
      authState: 0, // 授权状态
      employeeIdList: [] // 自定义可见范围选中的人
    }
    applicationFormRef.value?.clearValidate()
    oldRow.value = {}
  }
})

const openSelectDep = () => {
  SelectDepartmentPersonnelRef.value.open(applicationForm.value.employeeIdList)
}

const handleSuccess = (uploadFile: any) => {
  applicationForm.value.imgUrl = uploadFile.data.url
  MsgSuccess('上传成功')
}

const personHandle = (e: any) => {
  applicationForm.value.employeeIdList = e
}

async function getOptions() {
  const options = await agent.getCategorizeOptions()
  if (Array.isArray(options)) {
    perTypeList.value = [...options]
  }
}

/**
 * 处理头像上传前的验证逻辑
 *
 * 该函数在用户选择头像文件后、文件上传之前被调用，用于验证文件类型和大小是否符合要求。
 *
 * @param {File} uploadFile - 当前上传的文件对象，包含文件的基本信息如名称、大小、类型等。
 * @returns {boolean} - 如果文件符合要求返回 true，否则返回 false。
 */
const handleBeforeAvatarUpload = (uploadFile: any) => {
  const isJpgOrPng = uploadFile.type === 'image/jpeg' || uploadFile.type === 'image/png'
  const isLt100KB = uploadFile.size / 1024 < 100

  if (!isJpgOrPng) {
    MsgError('仅支持.png 和.jpg 格式的文件')
    return false
  }
  if (!isLt100KB) {
    MsgError('文件大小不能超过 100KB')
    return false
  }
  return true
}

const handlePictureCardPreview: UploadProps['onPreview'] = (url: any) => {
  PreviewdialogImageUrl.value = url
  PreviewDialogVisible.value = true
}

const handelDetails = (id: any) => {
  getDetails({ id }).then((res: any) => {
    if(res.data.isSuccess && Array.isArray(res.data.data.employeeList)) {
      applicationForm.value.employeeIdList = res.data.data.employeeList.map((el: any) =>{
        return {
          id: el.id,
          name: el.realName
        }
      } )
      initFormData.value = cloneDeep(applicationForm.value);
    }
  })
}

const open = (row: any) => {
  getOptions()
  dialogVisible.value = true
  const { id, maxId, name, applicationDesc, imgUrl, classification, type, authState, employeeIdList } = row
  handelDetails(id)
  oldRow.value = row
  applicationForm.value = {
    id,
    maxId,
    name, // 	智能体名称
    applicationDesc, // 智能体描述
    imgUrl, // 图片地址
    classification, // 分类
    type, // 智能体类型
    authState, // 授权状态
    employeeIdList // 自定义可见范围选中的人
  }
  initFormData.value = cloneDeep(applicationForm.value);
}

const submitHandle = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  const valid = await formEl.validate()
  if (!valid) return
  if (applicationForm.value.authState === 1 && applicationForm.value.employeeIdList.length === 0)
    return
  loading.value = true
  const params: any = {
    id: applicationForm.value.id,
    maxId: applicationForm.value.maxId,
    name: applicationForm.value.name,
    applicationDesc: applicationForm.value.applicationDesc,
    imgUrl: applicationForm.value.imgUrl,
    classification: applicationForm.value.classification,
    type: applicationForm.value.type,
    authState: applicationForm.value.authState
  }
  if (applicationForm.value.authState === 1) {
    params.employeeIdList = applicationForm.value.employeeIdList.map((el: any) => el.id)
  }
  updateAiApplication(params)
    .then((res: any) => {
      if (+res.data.code === 0) {
        MsgSuccess('修改成功')
        // if (isWorkFlow(applicationForm.value.type)) {
        //   router.push({ path: `/application/${res.data.id}/workflow` })
        // } else {
        //   router.push({ path: `/application/${res.data.id}/${res.data.type}/setting` })
        // }
        dialogVisible.value = false
        emit('refresh')
      }
    })
    .catch((err) => {
      MsgError(err.response.data.msg)
    })
    .finally(() => {
      loading.value = false
    })
}
const initFormData: any = ref({})

function closeConfirm (done: () => void) {
  if (isEqual(applicationForm.value, initFormData.value)) {
    return close(done)
  }
  MsgConfirm('提示', '修改后的信息未保存，确定不保存并关闭弹窗？').then(() => {
    close(done)
  })
}

function close (done: () => void) {
  isFunction(done) && done()
  dialogVisible.value = false
}

defineExpose({ open })
</script>
<style lang="scss" scoped>
.radio-card {
  line-height: 22px;
  &.active {
    border-color: var(--el-color-primary);
    color: var(--el-color-primary);
  }
}
.acatar_box {
  padding-top: 18px;
  position: relative;
  .avatar_text {
    position: absolute;
    width: 100%;
    left: 0;
    top: -10px;
    color: #8c8c8c;
  }
}
.avatar-uploader {
  width: 100%;
  position: relative;
  &-content {
    display: flex;
    flex-direction: row;
    font-weight: 400;
    font-size: 14px;
    color: #8c8c8c;
    line-height: 20px;

    &-right {
      position: absolute;
      top: -48px;
      right: 0;
      width: 80px;
      height: 80px;
      border-radius: 50%;
      border: 1px solid #dfe0e3;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-weight: 400;
      font-size: 12px;
      color: #fff;
      overflow: hidden;
      .avatar-move {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
      }
      img {
        width: 14px;
      }
      .avatar {
        width: 80px;
        height: 80px;
      }
    }

    &-def{
      background: url(../../../assets/agent/def_agent.svg);
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
      z-index: 1;
    }
    &-def-img{
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      position: absolute;
    }
    &-def::before{
      content: '';
      width: 100%;
      height: 100%;
      position: absolute;
      top:0;
      left: 0;
      background: rgba(0,0,0,0.6);
      z-index: 0;
    }
  }
}
.personnel-list {
  width: 100%;
  display: flex;
  padding: 6px 12px;
  border: 1px solid #dfe0e3;
  border-radius: 6px;
  align-items: center;
  justify-content: space-between;
  &-content {
    flex: 1;
    line-height: 20px;
    max-width: 430px;
    font-size: 14px;
    color: #191919;
  }
  &-right {
    width: 70px;
    font-size: 12px;
    line-height: 20px;
    color: #3067ef;
    text-align: right;
    cursor: pointer;
    display: flex;
    &-num {
      overflow: hidden;
      max-width: 150px;
      margin-right: 6px;
    }
  }
}
</style>
